/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package util.task.quartz;

import java.text.ParseException;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.quartz.impl.triggers.SimpleTriggerImpl;

/**
 *
 * @author rdelacruz
 */

/*
//cron expressions
http://www.quartz-scheduler.org/documentation/quartz-2.2.x/tutorials/crontrigger

//Ejemplos:
http://quartznet.sourceforge.net/apidoc/2.0/html/html/8543b17a-e2d4-bfb3-b8d2-ffcdc8a342c7.htm

Expression		Meaning
"0 0 12 * * ?"" />		Fire at 12pm (noon) every day" />
"0 15 10 ? * *"" />		Fire at 10:15am every day" />
"0 15 10 * * ?"" />		Fire at 10:15am every day" />
"0 15 10 * * ? *"" />		Fire at 10:15am every day" />
"0 15 10 * * ? 2005"" />		Fire at 10:15am every day during the year 2005" />
"0 * 14 * * ?"" />		Fire every minute starting at 2pm and ending at 2:59pm, every day" />
"0 0/5 14 * * ?"" />		Fire every 5 minutes starting at 2pm and ending at 2:55pm, every day" />
"0 0/5 14,18 * * ?"" />		Fire every 5 minutes starting at 2pm and ending at 2:55pm, AND fire every 5 minutes starting at 6pm and ending at 6:55pm, every day" />
"0 0-5 14 * * ?"" />		Fire every minute starting at 2pm and ending at 2:05pm, every day" />
"0 10,44 14 ? 3 WED"" />		Fire at 2:10pm and at 2:44pm every Wednesday in the month of March." />
"0 15 10 ? * MON-FRI"" />		Fire at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday" />
"0 15 10 15 * ?"" />		Fire at 10:15am on the 15th day of every month" />
"0 15 10 L * ?"" />		Fire at 10:15am on the last day of every month" />
"0 15 10 ? * 6L"" />		Fire at 10:15am on the last Friday of every month" />
"0 15 10 ? * 6L"" />		Fire at 10:15am on the last Friday of every month" />
"0 15 10 ? * 6L 2002-2005"" />		Fire at 10:15am on every last Friday of every month during the years 2002, 2003, 2004 and 2005" />
"0 15 10 ? * 6#3"" />		Fire at 10:15am on the third Friday of every month" />

*/


//Iniciar Quartz con un Servlet Simple
//http://www.easywayserver.com/blog/java-job-scheduling-in-web-application-with-quartz-api/

//Instanciar Trigger y JobDetail de Quartz con XML
//http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=quartz


public class TestTaskUtil {
    
    public static void main(String[] args) {        
        try {
            test1();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public static void test1() throws Exception {       
        JobDetail jDetail = new JobDetailImpl( 
            "Mi tarea", 
            Scheduler.DEFAULT_GROUP,
            TareaPrueba.class);       
        
        String patron;
        patron = "0 0 16,17 * * ?";//a las 4pm y 5pm, cada dia
        //patron = "0/3 * * * * ?"; //cada 3 segundos
        
        CronTriggerImpl crTrigger = new CronTriggerImpl(
            "MiTrigger", 
            Scheduler.DEFAULT_GROUP, 
            patron);
        
        
        Scheduler sd = StdSchedulerFactory.getDefaultScheduler();
        sd.scheduleJob(jDetail, crTrigger);
        sd.start();
    }
    
    //http://sg.com.mx/revista/18/una-introduccion-quartz-calendarizacion-tareas-java#.U4ZWavnh0fQ
    public static void test2() throws Exception {       
            
        System.out.println("Iniciando Scheduler...");

        // Creacion de una instacia de Scheduler
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();             
        scheduler.start(); 
        // Creacion una instacia de JobDetail
        JobDetail jobDetail = new JobDetailImpl( 
        "HolaMundoJob", 
        Scheduler.DEFAULT_GROUP,
        TareaPrueba.class);

        // Creacion de un Trigger donde indicamos 
        // que el Job se                        
        Trigger trigger = new SimpleTriggerImpl( 
        "HolaMundoTrigger", 
        Scheduler.DEFAULT_GROUP, 
        10, 2000);//Se ejecutará de inmediato y luego 10 veces cada 2 segundos

        /*
        SimpleTriggerImpl trigger1 = new SimpleTriggerImpl();
            trigger1.setName("HolaMundoTrigger");
            trigger1.setGroup(Scheduler.DEFAULT_GROUP);
            trigger1.setRepeatCount(10);
            trigger1.setRepeatInterval(5000);
        */
        
        //proceso en automático el último día de cada mes a las 6:30 pm que es la hora en que se termina la jornada laboral
        Trigger trigger2 = new CronTriggerImpl(
                "HolaMundoTrigger", 
                Scheduler.DEFAULT_GROUP, 
                "0 30 6 L * ?");        
        
        // Registro dentro del Scheduler
        scheduler.scheduleJob(jobDetail, trigger);

        // Damos tiempo a que el Trigger registrado 
        //termine su periodo 
        // de vida dentro del scheduler

        Thread.sleep(50000);//50 SEGUNDOS DE VIDA

        // Detenemos la ejecución de la 
        // instancia de Scheduler 
        scheduler.shutdown();
     
    }
    
    //http://www.easywayserver.com/blog/java-job-scheduling-in-web-application-with-quartz-api/
    public static void test3() throws SchedulerException, ParseException, InterruptedException {
        SchedulerFactory sf = new StdSchedulerFactory();
        
        Scheduler sd = sf.getScheduler();        
        //sd.start();
        
        //JobDetail jDetail = new Job("Newsletter", "NJob", MiTarea.class);
        JobDetailImpl jDetail = new JobDetailImpl();
        jDetail.setName("MiTarea");
        jDetail.setGroup(Scheduler.DEFAULT_GROUP);
        jDetail.setJobClass(TareaPrueba.class);        
        //jDetail.getJobDataMap().put("outputFile", "d:/vm_status.txt");         
        
        SimpleTriggerImpl trigger = new SimpleTriggerImpl();
        trigger.setName("MiTrigger");
        trigger.setGroup(Scheduler.DEFAULT_GROUP);
        trigger.setRepeatCount(10);
        trigger.setRepeatInterval(5000);        
        /*        
        Trigger trigger = new SimpleTriggerImpl( 
            "HolaMundoTrigger", 
            Scheduler.DEFAULT_GROUP, 
            10, 5000);
        */
                
        //CronTrigger crTrigger = new CronTriggerImpl("cronTrigger", "NJob", "0/2 * * * * ?");
        CronTriggerImpl crTrigger = new CronTriggerImpl(
                "MiTrigger", 
                Scheduler.DEFAULT_GROUP, 
                "0/3 * * * * ?");
        


        /*
        //SALE ERROR:
        CronTriggerImpl crTrigger = new CronTriggerImpl();
        crTrigger.setName("MiTrigger");//SchedulerException: nombre no puede ser nulo
        crTrigger.setGroup(Scheduler.DEFAULT_GROUP);        
        //"0 0 12 * * ?" Fire at 12pm (noon) every day
        //"0/2 * * * * ?" Fire at every 2 seconds every day    
        //crTrigger.setCronExpression("0/3 * * * * ?");
        crTrigger.setCronExpression("0/3 0 0 * * ?");
        */
        
        sd.scheduleJob(jDetail, crTrigger);
        sd.start();
        
        //Thread.sleep(10L * 1000L);//dormir 10 seg        
        //sd.shutdown();
    }
    
    public static void test4() {
        try {
            // Creacion de una instacia de Scheduler
                Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); 
            System.out.println("Iniciando Scheduler...");
            scheduler.start(); 
            // Creacion una instacia de JobDetail
            JobDetail jobDetail = new JobDetailImpl( 
            "HolaMundoJob", 
            Scheduler.DEFAULT_GROUP,
            TareaPrueba.class);

            // Creacion de un Trigger donde indicamos 
            //que el Job se 
            // ejecutara de inmediato y a partir de ahi en lapsos
            // de 5 segundos por 10 veces mas. 
                Trigger trigger = new SimpleTriggerImpl( 
            "HolaMundoTrigger", 
            Scheduler.DEFAULT_GROUP, 
            10, 5000);

            // Registro dentro del Scheduler
            scheduler.scheduleJob(jobDetail, trigger);

            // Damos tiempo a que el Trigger registrado 
            //termine su periodo 
            // de vida dentro del scheduler
            Thread.sleep(60000);

            // Detenemos la ejecución de la 
            // instancia de Scheduler 
            scheduler.shutdown();

        } catch(Exception e) {
            System.out.println("Ocurrió una excepción");
        }
    }  

}
